<script setup>
import { reactive,ref,onMounted, computed } from 'vue';
import {useUserStore}from '@/stores/user';
import { deleteUserById, updatePassword, updateUserInfo,findById} from '@/api/user';
import { ElMessage, ElForm, ElInput, ElDialog, ElFormItem, ElRadio, ElUpload, ElButton, ElIcon } from 'element-plus'
import { Plus, Upload } from '@element-plus/icons-vue'
import {useRoute, useRouter} from 'vue-router'
import { uploadFileReq } from '@/api/image';

    const route = useRoute()
    const store = useUserStore()
    //获取userStore对象
    const userStore = useUserStore()
    const router = useRouter()
    //用户数据对象
    const userData =ref({})
    
    // 密码修改对话框相关
    const passwordDialogVisible = ref(false)
    const passwordForm = reactive({
      uid: userStore.user.uid,
      oldPassword: '',//旧密码
      newPassword: '',//新密码
      confirmPassword: '',
      securityAnswer: '' // 密保问题答案字段
    })
    const passwordFormRef = ref(null)
    const passwordRules = {
      oldPassword: [
        { required: true, message: '请输入旧密码', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== passwordForm.newPassword) {
              callback(new Error('两次输入的密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ],
      securityAnswer: [ // 添加密保问题答案验证规则
        { required: true, message: '请输入密保问题答案', trigger: 'blur' }
      ]
    }
    // 打开密码修改对话框
    const openPasswordDialog = () => {
      passwordDialogVisible.value = true
    }
    // 关闭密码修改对话框并重置表单
    const closePasswordDialog = () => {
      passwordDialogVisible.value = false
      passwordFormRef.value?.resetFields()
    }
    // 提交密码修改
    const submitPasswordChange = ()=>{
      updatePassword(passwordForm).then((res) => {
        if(res.status === 200){
          ElMessage.success('密码修改成功')
          closePasswordDialog()
          // 通常修改密码后应该重新登录
          // 可以根据实际需求决定是否添加以下代码
          // router.push('/login')
          // store.saveToken('')
        }else{
          ElMessage.error('密码修改失败:'+res.message)
        }
      })
    }
    // 编辑用户信息对话框相关
    const editDialogVisible = ref(false)
    const editForm = reactive({
      uimage: null,
      uid: 0,
      uname: '',
      ugender: '',
      utel: '',
      uemail: '',
      uinfo: '',
    })
    const editFormRef = ref(null)
    const editRules = {
      uname: [
        { required: true, message: '请输入姓名', trigger: 'blur' }
      ],
      utel: [
        { required: true, message: '请输入电话', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ],
      uemail: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ]
    }

    // 打开编辑对话框
    const openEditDialog = () => {
      // 复制当前用户数据到编辑表单
      editForm.uid = userData.value.uid
      editForm.uname = userData.value.uname
      editForm.ugender = userData.value.ugender
      editForm.utel = userData.value.utel
      editForm.uemail = userData.value.uemail
      editForm.uinfo = userData.value.uinfo
      editForm.uimage = userData.value.imagePath
      editDialogVisible.value = true
    }

    // 关闭编辑对话框并重置表单
    const closeEditDialog = () => {
      editDialogVisible.value = false
      editFormRef.value?.resetFields()
    }

    // 提交用户信息修改
    const submitEditForm = async () => {
      try {
        await editFormRef.value?.validate()
        //调用更新用户信息的API
        updateUserInfo(editForm).then((res) => {
          if(res.status === 200){
            ElMessage.success('用户信息更新成功')
            queryPage()
            // 假设store中有saveUser方法可以更新用户信息
            userStore.saveUser(userData.value)
            closeEditDialog()
          }else{
            ElMessage.error('用户信息更新失败'+res.msg)
          }
        })
      } catch (error) {
        ElMessage.error('用户信息更新失败')
      }
    }

  //头像缩略图数据模型
  function handleChangeFile(uploadFile){
      //获得当前选中的图片对象
      let file = uploadFile.raw;
      //将file的图片地址 赋值给缩略图数据模型
      editForm.uimage = URL.createObjectURL(file)

      //上传逻辑
      uploadFileFunc(file);
  }
  function uploadFileFunc(file){
    //创建虚拟表单 用于装载上传文件
    let formData = new FormData();
    formData.append("file",file);

    // //发送图片
    uploadFileReq(formData)
    .then(data =>{
        //上传成功 将上传图片的url赋值给数据模型
        userStore.user.uimage = data.message;
    })
  }

    //onMounted钩子函数，获取id值
    onMounted(()=>{
        queryPage()
    })
    //查询用户信息
    const queryPage=()=>{
      findById(userStore.user.uid).then((res) => {
        if(res.status === 200){
          userData.value = res.data
        }
      })
    }
    //编辑用户信息
    const editUserData =(id)=>{
        // 不再使用路由跳转，而是打开编辑对话框
        openEditDialog()
    }
    //确认删除
    const HandleDeleteUserConfirm = (id) => {
        deleteUserById(id).then(() => {
            router.push('/login')
            store.saveToken('')
        })
    }
    const HandleDeleteUserCancel = () => {
    console.log('取消删除')
    }
    const UpdatePassword= () => {
        // 不再使用路由跳转，而是打开对话框
        openPasswordDialog()
    }

</script>
<template>
    <!-- 个人信息 -->
    <el-row>
        <el-col :span="3"></el-col>
        <el-col :span="18">
            <el-card style="width: 100%;  border-radius: 10px; /* 圆角大小，数值越大圆角越明显 */overflow: hidden; /* 避免卡片内容超出圆角范围 */">
                <el-row>
                    <el-col :span="17"><strong style="width: 100%; font-size: 20px;height: 50px;">个人信息</strong></el-col>
                    <!-- 创建时间 -->
                    <el-col :span="7">
                        <div style="height: 50px;display: flex;align-items: center;">
                            <span >创建时间：{{userData.uregtime }}</span>
                        </div>
                    </el-col>
                </el-row>
                <el-row style="margin-top: 20px;">
                    <!-- 头像 -->
                    <el-col :span="3">
                         <div style="width: 100%;height: 50px;display: flex;align-items: center;justify-content: center;">
                            <el-avatar :size="60" :src="userData.uimage" />
                         </div>
                    </el-col>
                    <!--昵称、性别、总积分、 -->
                    <el-col :span="14">
                        <el-row>
                            <el-col :span="8" style="height: 50px;display: flex;align-items: center;">
                                <strong >昵称：{{ userData.uname }}</strong>
                            </el-col>
                            <el-col :span="8" style="height: 50px;display: flex;align-items: center;">
                                <strong>性别：{{ userData.ugender }}</strong>
                            </el-col>
                            <el-col :span="8" style="height: 50px;display: flex;align-items: center;">
                                <strong>总积分：{{ userData.uintegral }}</strong>
                            </el-col>
                        </el-row>
                            </el-col>
                            <el-col :span="7"></el-col>
                </el-row>
                <el-row>
                    <el-col :span="3"></el-col>
                    <!--联系方式、邮箱 -->
                    <el-col :span="14">
                        <el-row>
                            <el-col :span="12" style="height: 50px;display: flex;align-items: center;">
                                <strong >联系方式：{{ userData.utel }}</strong>
                            </el-col>
                            <el-col :span="12" style="height: 50px;display: flex;align-items: center;">
                                <strong>邮箱：{{ userData.uemail }}</strong>
                            </el-col>
                        </el-row>
                    </el-col>
                    <el-col :span="7"></el-col>
                </el-row>
                <el-row style="margin-top: 10px;">
                    <el-col :span="3"></el-col>
                    <!-- 个性签名 -->
                    <el-col :span="14">
                        <strong style="width: 100%;height: 50px;">个性签名：{{ userData.uinfo }}</strong>
                    </el-col>
                    <el-col :span="7"></el-col>
                </el-row>
                <el-row style="margin-bottom: 10px;">
                    <el-col :span="17"></el-col>
                    <el-col :span="7">
                        <div style="display: flex;justify-content: center;align-items: center;">
                            <el-button type="primary" @click="editUserData(userData.id)">编辑</el-button>
                            <el-button type="warning" @click="UpdatePassword()">修改密码</el-button>
                            <el-popconfirm confirm-button-text="确定" cancel-button-text="取消" icon-color="#626AEF" title="是否确认删除?"
                                @confirm="HandleDeleteUserConfirm(userStore.user.userId)" @cancel="HandleDeleteUserCancel">
                                <template #reference>
                                    <el-button type="danger"> 注销用户 </el-button>
                                </template>
                            </el-popconfirm>
                        </div>
                    </el-col>
                </el-row>
            </el-card>
        </el-col>
        <el-col :span="3"></el-col>        
    </el-row>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="passwordDialogVisible"
      title="修改密码"
      width="400px"
      center
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input
            v-model="passwordForm.oldPassword"
            type="password"
            placeholder="请输入旧密码"
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
          />
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
          />
        </el-form-item>
        <el-form-item label="密保问题">
          <el-text>{{ userData.upwdask }}</el-text>
        </el-form-item>
        <el-form-item label="密保答案" prop="securityAnswer">
          <el-input
            v-model="passwordForm.securityAnswer"
            placeholder="请输入您的密保问题答案"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closePasswordDialog">取消</el-button>
          <el-button type="primary" @click="submitPasswordChange">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑用户信息对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑用户信息"
      width="600px"
      center
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="100px"
        style="max-width: 500px;"
      >
        <!-- 头像上传 -->
        <el-form-item label="头像">
          <div class="avatar-uploader">
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :auto-upload="false"
              :on-change="handleChangeFile"
            >
                <img v-if="editForm.uimage" :src="editForm.uimage" class="avatar" />       
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </div>
        </el-form-item>

        <!-- 姓名 -->
        <el-form-item label="姓名" prop="uname">
          <el-input
            v-model="editForm.uname"
            placeholder="请输入姓名"
          />
        </el-form-item>

        <!-- 性别 -->
        <el-form-item label="性别">
          <el-radio-group v-model="editForm.ugender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 电话 -->
        <el-form-item label="电话" prop="utel">
          <el-input
            v-model="editForm.utel"
            placeholder="请输入手机号码"
          />
        </el-form-item>

        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="uemail">
          <el-input
            v-model="editForm.uemail"
            placeholder="请输入邮箱地址"
          />
        </el-form-item>

        <!-- 个人简介 -->
        <el-form-item label="个人简介">
          <el-input
            v-model="editForm.uinfo"
            type="textarea"
            placeholder="请输入个人简介"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeEditDialog">取消</el-button>
          <el-button type="primary" @click="submitEditForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

</template>

<style scoped>
    .cardStyle{
        width: 100%;
        min-height: 40px;
        margin: 10px;
    }
    .cardStyle {
        transition: box-shadow 0.3s ease, transform 0.3s ease;
    }

    .cardStyle:hover {
        cursor: pointer;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        transform: translateY(-5px);
    }
    .cardStyle:active {
        background-color: rgba(0, 0, 0, 0.05); /* 背景颜色变暗 */
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); /* 阴影变浅 */
        transform: translateY(-2px); /* 减少上升效果 */
    }
    .avatar-uploader .el-avatar {
        cursor: pointer;
        transition: all 0.3s;
        border: 1px dashed #dcdfe6;
    }
    .avatar-uploader .el-avatar:hover {
        border-color: #409eff;
        transform: scale(1.1);
    }
    /* 头像上传容器样式 */
.avatar-uploader {
  position: relative;
  display: inline-block;
  cursor: pointer;
}

/* 头像图片样式 */
.avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover; /* 保持图片比例并填充容器 */
  border: 2px solid #e5e7eb;
  transition: all 0.3s ease;
}

/* 上传图标容器样式 */
.avatar-uploader-icon {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  background-color: #f3f4f6;
  border: 2px dashed #d1d5db;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #6b7280;
  font-size: 24px;
  transition: all 0.3s ease;
}

/* 悬停效果 - 增强交互体验 */
.avatar-uploader:hover .avatar {
  border-color: #409eff; /* Element UI 主题色 */
  box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.1);
}

.avatar-uploader:hover .avatar-uploader-icon {
  border-color: #409eff;
  color: #409eff;
  background-color: #ecf5ff; /* 浅蓝色背景，与主题呼应 */
}

/* 隐藏上传组件默认样式 */
.avatar-uploader .el-upload {
  display: block;
}

/* 上传中状态样式 */
.avatar-uploader-loading {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 响应式调整 - 在小屏幕上适配 */
@media (max-width: 768px) {
  .avatar,
  .avatar-uploader-icon {
    width: 100px;
    height: 100px;
  }
}
</style>